package von.seiji.cn.other;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class HttpServer implements Runnable {
    //服务器监听
    private ServerSocket serverSocket;

    public HttpServer(int port) {
        try {
            serverSocket = new ServerSocket(port);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void run() {
        System.out.println("Server Start...");
        while (true) {    //一直监听，知道收到停止的命令
            Socket socket = null;
            try {
                socket = serverSocket.accept();    //如果没有请求，会在这里等待，有客户端请求的时候才会继续往下执行

                BufferedReader bufferedReader = new BufferedReader(
                        new InputStreamReader(socket.getInputStream()));    //获取输入流
                String line = null;
                StringBuffer buffer = new StringBuffer();
                while ((line = bufferedReader.readLine()) != null) {
                    buffer.append(line);
                }
                doEcho(buffer.toString());
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (socket != null) {
                    try {
                        socket.close();
                    } catch (IOException e) {
                        System.out.println("服务端端 finally 异常:" + e.getMessage());
                    }
                }
            }
        }
    }

    /*
     * 讲收到的信回写给客户端
     */
    private void doEcho(String record) throws IOException {
        System.out.println("服务端接收数据：");
        System.out.println("------------------------------");
        System.out.println(record);
    }


}

class Serverluancher {
    public static void main(String[] args) {
        HttpServer httpServer = new HttpServer(7777);
        new Thread(httpServer).start();
    }
}